package com.geekhalo.demo.mq.disorder.fix.c1;

import com.geekhalo.demo.mq.disorder.OrderCreatedEvent;
import com.geekhalo.demo.mq.event.fix.OrderPaidEvent;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.event.TransactionalEventListener;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Service
public class RocketMQProducer {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    // 创建一个ScheduledExecutorService实例
    private ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    @TransactionalEventListener
    public void handle(OrderCreatedEvent event){
        rocketMQTemplate.convertAndSend("order_created_event", event);
    }

    @TransactionalEventListener
    public void handle(OrderPaidEvent event){
        // 创建Runnable任务
        Runnable task = () -> {
            rocketMQTemplate.convertAndSend("order_paid_event", event);
        };
        // 使用ScheduledExecutorService schedule方法在5秒后执行任务
        executor.schedule(task, 5, TimeUnit.SECONDS);
    }
}